from strategy.models import Strategy
from strategy.migrations import strategy_list
from django.core.management.base import BaseCommand
from django.db import transaction


class Command(BaseCommand):
    help = '裁剪策略'
    StrategyNameDict = {
        # "异地认证": [2, 3],
        "认证失败冻结": [2, 3],
        "闲时登出": [2, 3],
        "异常时间登录": [2, 3],
        "单次认证失效": [2, 3],
        # "新设备认证": [2],
        "其他用户登录": [2],
        "单设备登录": [2],
        "禁止运行虚拟机软件": [2],
        "禁止运行录屏软件": [2],
        "禁止运行远控软件": [2],
        "杀毒软件需调起运行": [2],
        "防火墙需调起运行": [2],
        "设备需运行在安全域（异常设备登录）": [2],
        "资源请求频次过高": [0],
        "资源请求越权": [0],
        "资源请求总量过高": [0],
        }

    def add_arguments(self, parser):
        pass

    @transaction.atomic()
    def handle(self, strategy_name_dict=StrategyNameDict, *args, **options):
        Strategy.objects.all().delete()
        strategy_list.append(
            Strategy(
                name='其他用户登录',
                description='终端注册信息与用户不一致时不允许登录',
                level=2,
                channel=2,
                weight=5,
                category='身份认证',
                uid=f'STG/AUTH-22'
            )
        )

        Strategy.objects.bulk_create(strategy_list)

        # 剔除策略名称不做筛选列表里面的数据
        strategy_name_list = list(strategy_name_dict.keys())
        Strategy.objects.exclude(name__in=strategy_name_list).all().delete()
        for strategy_name_ in strategy_name_list:
            channel_list = strategy_name_dict[strategy_name_]
            strategy_name_info_list = Strategy.objects.filter(name=strategy_name_).all()
            for strategy_name_info in strategy_name_info_list:
                if strategy_name_info.channel not in channel_list:
                    strategy_name_info.delete()

        print("Done")